package gui.chatarea;

import java.util.TreeMap;
import java.util.regex.Pattern;

import utils.Configuration;

public final class HTMLChatParser {
	
	private static Pattern URL_PATTERN = Pattern.compile("(((http(s?)://)|(www.))[^ ]+)") ;
	private static String URL_REPLACER = "<a class=\"" + HTMLChatDocument.URL_LINK_CLASS + "\" href=\"$1\">$1</a>" ;
	
	private static String EMOTICONS_FOLDER = "emoticons" ;
	private static TreeMap <String, String> EMOTICON_PATTERN = new TreeMap <String, String> () ;
	
	private static String[] REGEXP_TO_ESCAPE = {"(", ")", "[", "]", "{", "}", "?", "^", "$", ".", "*"} ;
	
	/**
	 * Escape character from the specified string.
	 * 
	 * @param str
	 * @return
	 */
	private static String escapeForRegexp (String str) {
		String res = str ;
		for (String ch : REGEXP_TO_ESCAPE) {
			res = res.replace(ch, "\\" + ch) ;
		}
		return res ;
	}
	
	static {
		String[] pattern = {":)", ";)", ":(", ":D", ":O", "^^", ":P",":punk:", ":ninja:"} ;
		String[] filename = {"smile", "wink", "sad", "laugh", "ohmy", "happy", "tongue", "punk", "ninja"} ;
		String emoticonsFolder = Configuration.getImageFolder() + "/" + EMOTICONS_FOLDER ;
		for (int i=0; i<pattern.length; i++) {
			EMOTICON_PATTERN.put(escapeForRegexp(pattern[i]), "<img src=\"file:" + emoticonsFolder + "/" + filename[i] + ".gif\" />") ;
		}
	}

	/**
	 * Add tag to the specified message and escape special character
	 * 
	 * @param message
	 * @return
	 */
	public static String addTag(String message) {
		String res = message.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;") ; 
		res = URL_PATTERN.matcher(res).replaceAll(URL_REPLACER) ;
		for (String pat : EMOTICON_PATTERN.keySet()) {
			res = Pattern.compile(pat).matcher(res).replaceAll(EMOTICON_PATTERN.get(pat)) ;
		}
		return res;
	}

}
